package ua.yandex.prodcons.threads;

public class CircularBuffer {

    private final int size;
    private int freePlace;
    private int start;
    private int lastNoFilled;
    private final Object[] array;

    CircularBuffer(int n) {
        size = n;
        freePlace = n;
        array = new Object[n];
        start = 0;
        lastNoFilled = 0;
    }

    public void add(Object data) throws InterruptedException {
        synchronized (new Object()) {
            while (freePlace == 0) {
                wait();
            }
            array[lastNoFilled] = data;
            lastNoFilled++;
            lastNoFilled %= size;
            freePlace--;
            notifyAll();
        }
    }

    synchronized public Object get() throws InterruptedException {
        while (freePlace == size) {
            wait();
        }
        Object result = array[start];
        start++;
        start %= size;
        freePlace++;
        notifyAll();
        return result;
    }

    /* public void write() {
     int temp = start;
     if (start != lastNoFilled) {
     while (temp != lastNoFilled) {
     System.out.println(array[temp]);
     temp++;
     temp %= size;
     }
     } else {
     temp = start;
     System.out.println(array[temp]);
     temp++;
     temp %= size;
     while (temp != lastNoFilled) {
     System.out.println(array[temp]);
     temp++;
     temp %= size;
     }
     }
     }*/
}
